<template>
  <el-dialog v-if="load" :title="title" v-model="visible" align-center width="773px" @close="handleClose" :close-on-click-modal="false">
    <el-form :model="formData" label-width="140px" :rules="rules" ref="ruleFormRef" inline class="formw200">
      <el-form-item label="平台:" prop="platform_id">
        <el-select v-model="formData.platform_id" class="input" collapse-tags placeholder="平台" disabled>
          <el-option v-for="(d, i) in platformList" :key="i" :label="d.platform_name" :value="d.platform_id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="类目/产品类目:" prop="channel_sku_category" class="mr-[0]">
        <el-input class="input" v-model.trim="formData.channel_sku_category" placeholder="请输入"> </el-input>
      </el-form-item>

      <el-form-item label="币种:" prop="currency" class="mr-[0]">
        <el-select v-model="formData.currency" class="input mr-[6px]" clearable placeholder="币种">
          <el-option v-for="(d, i) in originOption.countryOpt" :key="i" :label="d.label" :value="d.label"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="订单金额范围:" style="margin-bottom: 0">
        <div v-for="(item, idx) in formData.commission_range_config" :key="idx">
          <el-form-item class="mr-[2px]" :prop="`commission_range_config.${idx}.lowest_selling_price`" :rules="[{ required: true, message: '请输入' }]">
            <el-input class="w-[90px]" type="number" v-model="item.lowest_selling_price" placeholder="请输入" />
          </el-form-item>
          <span class="text-gray-500 mb-[18px] mx-[4px]">-</span>
          <el-form-item class="ml-[2px] mr-[4px]" :prop="`commission_range_config.${idx}.highest_selling_price`" :rules="[{ required: true, message: '请输入' }]">
            <el-input class="w-[90px]" type="number" v-model="item.highest_selling_price" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="佣金比例(%)" label-width="106" :prop="`commission_range_config.${idx}.commission_rate`" :rules="[{ required: true, message: '请输入' }]">
            <el-input class="w-[90px]" v-model="item.commission_rate" placeholder="请输入"> </el-input>
          </el-form-item>
          <template v-if="!formData.id">
            <span class="dk-iconfont icon-CirclePlus cursor-pointer" style="font-size: 24px !important" @click="add"></span>
            <span class="dk-iconfont icon-CircleMinus cursor-pointer" style="font-size: 24px !important" @click="del(idx)"></span>
          </template>
        </div>
      </el-form-item>

      <el-form-item label="备注:" prop="remark" class="mr-[0]">
        <el-input class="input" v-model="formData.remark" placeholder="请输入" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"> </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, toRefs } from "vue"
import { getDetail, createCommission, updateCommission } from "../api"
import { ElMessage } from "element-plus"
import XEUtils from "xe-utils"
import { getPlatformOptions } from "@/api/public"

const ruleFormRef = ref()
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
  ruleTypeOption: {
    type: Object,
    default: [],
  },
})
const add = () => {
  formData.value.commission_range_config.push({})
}
const del = (idx) => {
  formData.value.commission_range_config.splice(idx, 1)
}
const data = reactive({
  formData: {
    platform_id: 3,
    commission_range_config: [{}],
  },
  isType: false,
  platformList: [],
  siteList: [],
  shopList: [],
})
const { formData, isType, platformList, siteList, shopList } = toRefs(data)
const { title, ruleTypeOption } = toRefs(props)
const emit = defineEmits(["close", "confirm"])
//清空sku
const clearSku = () => {
  formData.value.sku = ""
}
//是否为数字
const isNumberF = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!XEUtils.isNumber(value * 1)) {
      return callback(new Error("请输入数字"))
    } else {
      callback()
    }
  }
}
//订单金额范围
const priceRadius = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!XEUtils.isNumber(value * 1)) {
      return callback(new Error("请输入数字"))
    }
  }
}
const rules = reactive({
  platform_id: [{ required: true, message: "请选择平台", trigger: "change" }],
  channel_sku_category: [{ required: true, message: "类目不能为空", trigger: "blur" }],
  currency: [{ required: true, message: "请选择币种", trigger: "change" }],
})

// 打开弹窗
const open = (row = {}) => {
  if (!load.value) {
    load.value = true
  }
  if (row.id) {
    isType.value = true
    getDetail({ id: row.id }).then((res) => {
      loadings = reactive({})
      visible.value = true

      // getShop(res.data.platform_id, res.data.site)

      formData.value = {
        ...res.data,
        commission_range_config: [
          {
            lowest_selling_price: res.data.lowest_selling_price,
            highest_selling_price: res.data.highest_selling_price,
            commission_rate: res.data.commission_rate,
          },
        ],
      }
    })
  } else {
    formData.value = {
      platform_id: 3,
      commission_range_config: [{}],
    }

    loadings = reactive({})
    isType.value = false
    visible.value = true
  }
}
// 关闭弹窗
const close = () => {
  formData.value = {}
  ruleFormRef.value.resetFields()
  visible.value = false
}

const handleClose = () => {
  close()
  emit("close")
}
// 提交
const submit = () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      loadings.submit = true
      let params = { ...formData.value }
      // let keys = ["platform_id", "site", "shop_id", "additional_commission", "minimum_commission", "buy_it_now_commission", "commission_rate", "highest_selling_price", "lowest_selling_price"]
      // let params = {}
      // keys.forEach((key) => {
      //   params[key] = formData.value[key] || ""
      // })
      // if (!params.shop_id || !params.shop_id.length) {
      //   params.shop_id = shopList.value.map((v) => v.shop_id)
      // }
      if (isType.value) {
        params.id = formData.value.id
        updateCommission(params)
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else {
        createCommission(params)
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      }
    }
  })
}
defineExpose({ open })

// 获取平台
const getPlatform = async () => {
  try {
    const res = await getPlatformOptions()
    platformList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

onMounted(() => {
  getPlatform()
  getOption()
})
const originOption = ref({})
import { getCurrency } from "@/api/public"
const getOption = async () => {
  originOption.value.countryOpt = (await getCurrency()).data
}
</script>
<style lang="scss" scoped>
.formw200 {
  .el-form-item {
    // width: 400px;
    margin-right: 12px;
    // .el-input{
    //   width: 400px;
    // }
  }
  .input {
    width: 400px;
  }
}
:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}
:deep(.el-input__inner) {
  line-height: 1px !important;
}
</style>
